﻿
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;

namespace Mockery.Core.CommonContainer
{
    public static class CommonContainerLocator
    {
        private static ICommonContainerBuilder _commonContainerBuilder;

        /// <summary>
        /// This method locates the common container builder with this project.  The common
        /// container allows to create a fresh container from the common container which
        /// avoids the overhead of locating the container each time.
        /// </summary>
        /// <returns></returns>
        public static ICommonContainerBuilder CreateBuilder()
        {
            if (_commonContainerBuilder == null)
            {
                var directoryCatalog = new DirectoryCatalog(".", "CommonContainer.Mockery.*.dll");
                var container = new CompositionContainer(directoryCatalog);

                var containerList =
                    new List<ICommonContainerBuilder>(container.GetExportedValues<ICommonContainerBuilder>());

                if (containerList.Count == 0) throw new ContainerBuilderNotFoundException();
                if (containerList.Count > 1) throw new TooManyContainerBuildersFound();

                _commonContainerBuilder = containerList[0];
            }

            return _commonContainerBuilder.New();
            
        }
    }
}
